package com.lfg.leetcode.leetcode1000;


public class No1200numEnclaves {
    public static void main(String[] args) {
        int[][] properties = {{0, 0, 0, 0}, {1, 0, 1, 0}, {0, 1, 0, 1}, {0, 0, 0, 0}};
        System.out.println(numEnclaves(properties));
    }

    public static void mark(int[][] grid, int i, int j) {
        if (grid[i][j] == 0 || grid[i][j] == 2) {
            return;
        }
        grid[i][j] = 2;
        if (i > 0) {
            mark(grid, i - 1, j);
        }
        if (i < grid.length - 1) {
            mark(grid,  i + 1, j);
        }
        if (j > 0) {
            mark(grid,  i, j - 1);
        }
        if (j < grid[i].length - 1) {
            mark(grid,  i, j + 1);
        }

    }

    public static int numEnclaves(int[][] grid) {
        int ret = 0;

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] != 1) {
                    continue;
                }
                if (i == 0 || i == grid.length - 1 || j == 0 || j == grid[i].length-1) {
                    mark(grid, i, j);
                }
            }
        }
        for (int i = 1; i < grid.length; i++) {
            for (int j = 1; j < grid[i].length; j++) {
                if (grid[i][j] == 1) {
                    ret++;
                }
            }
        }
        return ret;
    }

}

